import { defineStore } from "pinia";
import { ref, watch } from "vue";

function initState() {
  return {
    isCollapse: false,
    tags: [
      {
        path: '/home',
        name: 'home',
        label: '首页',
        icon: 'home'
      },
    ],
    currentMenu: null, // 当前选中的菜单
    menuList: [],
    token: "",
    routerList: [],
  };
}

export const useAllDataStore = defineStore('allData', () => {
  const state = ref(initState());

  watch(state, (newObj) => {
    if (!newObj.token) return;
    localStorage.setItem("store", JSON.stringify(newObj));
  }, { deep: true });

  function selectMenu(val) {
    if (val.name === 'home') {
      state.value.currentMenu = null;
    } else {
      state.value.currentMenu = val;
      let index = state.value.tags.findIndex(item => item.name === val.name);
      if (index === -1) {
        state.value.tags.push(val);
      }
    }
  }

  function undateTags(tag) {
    let index = state.value.tags.findIndex((item) => item.name === tag.name);
    if (index > -1) {
      state.value.tags.splice(index, 1);
    }
  }

  function updateMenuList(val) {
    state.value.menuList = val;
  }

  function addMenu(router, type) {
    if (type === 'refresh') {
      const stored = localStorage.getItem("store");
      if (stored) {
        try {
          state.value = JSON.parse(stored);
        } catch (e) {
          console.error("解析 localStorage 数据失败", e);
        }
      } else {
        return;
      }
    }

    const menu = state.value.menuList;
    const module = import.meta.glob('../views/**/*.vue');
    const routeArr = [];

    menu.forEach(item => {
      if (item.children) {
        item.children.forEach(val => {
          const url = `../views/${val.url}.vue`;
          if (module[url]) {
            val.component = module[url];
          }
        });
        routeArr.push(...item.children);
      } else {
        const url = `../views/${item.url}.vue`;
        if (module[url]) {
          item.component = module[url];
        }
        routeArr.push(item);
      }
    });

    state.value.routerList = [];
    const existingRoutes = router.getRoutes();
    existingRoutes.forEach((item) => {
      if (item.name === "main" || item.name === "login" || item.name === "404") {
        return;
      } else {
        router.removeRoute(item.name);
      }
    });

    routeArr.forEach((item) => {
      state.value.routerList.push(router.addRoute("main", item));
    });
  }

  function clean() {
    state.value.routerList.forEach((route) => {
      if (route && typeof route === 'function') {
        route(); // 移除监听器
      }
    });
    state.value = initState();
    localStorage.removeItem("store");
  }

  return {
    state,
    selectMenu,
    undateTags,
    updateMenuList,
    addMenu,
    clean,
  };
});